<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的分享</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #f5f5f5; color: #333; height: 100vh; overflow: hidden; }

        .file-container { padding: 0; height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
        .file-list { background: white; border-radius: 0; box-shadow: none; overflow: hidden; flex: 1; display: flex; flex-direction: column; position: relative; }
        .file-list-wrapper { flex: 1; overflow: hidden; }
        .file-table { width: calc(100% - 40px); margin: 0 20px; border-collapse: collapse; table-layout: fixed; overflow: hidden; }
        .file-table thead { position: sticky; top: 0; z-index: 10; }
        .file-table th { background: #f8f9fa; padding: 8px 16px; text-align: left; font-weight: 600; color: #666; border-bottom: 1px solid #dee2e6; white-space: nowrap; font-size: 13px; }
        .file-table td { padding: 8px 16px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; }
        .file-table tr:hover { background: #f8f9fa; }

        .file-table th:nth-child(1) { width: 5%; }
        .file-table th:nth-child(2) { width: 25%; }
        .file-table th:nth-child(3) { width: 20%; text-align: left !important; }
        .file-table th:nth-child(4) { width: 15%; text-align: left !important; }
        .file-table th:nth-child(5) { width: 15%; }
        .file-table th:nth-child(6) { width: 10%; text-align: center !important; }

        /* 文件名列特殊处理 */
        .file-table td:nth-child(2) { overflow: visible; white-space: normal; }
        /* 密码列样式 - 简洁样式 */
        .file-table td:nth-child(4) { 
            text-align: left; 
        }
        .password-display {
            color: #333;
            font-size: 13px;
            cursor: pointer;
        }
        .password-display:hover {
            color: #1976d2;
        }
        /* 操作列特殊处理 */
        .file-table td:nth-child(6) { overflow: visible; white-space: normal; }

        .file-item { display: flex; align-items: center; gap: 12px; overflow: hidden; }
        .file-icon { font-size: 20px; width: 24px; text-align: center; }
        .file-name { font-weight: 500; color: #333; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
        .file-actions { display: flex; gap: 8px; align-items: center; justify-content: center; }
        
        /* 文件操作按钮样式（使用action-item结构） */
        .file-actions .action-item { 
            position: relative; 
            cursor: pointer; 
            transition: all 0.2s; 
            padding: 4px; 
            border-radius: 6px; 
        }
        .file-actions .action-item:hover { 
            background: #f8f9fa; 
        }
        .file-actions .action-icon { 
            width: 22px; 
            height: 22px; 
            border: none; 
            border-radius: 50%; 
            background: #f8f9fa; 
            font-size: 12px; 
            cursor: pointer; 
            transition: all 0.2s; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
        }
        .file-actions .action-icon:hover { 
            transform: scale(1.1); 
        }
        .file-actions .action-icon.copy { 
            background: #e3f2fd; 
            color: #1976d2; 
        }
        .file-actions .action-icon.delete { 
            background: #ffebee; 
            color: #d32f2f; 
        }
        .file-action-icon { 
            width: 24px; 
            height: 24px; 
            border: none; 
            border-radius: 4px; 
            font-size: 12px; 
            cursor: pointer; 
            transition: all 0.2s; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            position: relative; 
        }
        .file-action-icon:hover { transform: scale(1.1); }
        .file-action-icon.copy { background: #e3f2fd; color: #1976d2; }
        .file-action-icon.delete { background: #ffebee; color: #d32f2f; }

        .file-action-icon::after {
            content: attr(data-tooltip) !important;
            position: absolute !important;
            bottom: -30px !important;
            left: 50% !important;
            transform: translateX(-50%) !important;
            background: rgba(0, 0, 0, 0.8) !important;
            color: white !important;
            padding: 4px 8px !important;
            border-radius: 4px !important;
            font-size: 12px !important;
            white-space: nowrap !important;
            opacity: 0 !important;
            visibility: hidden !important;
            transition: opacity 0.3s, visibility 0.3s !important;
            z-index: 1000 !important;
        }

        .file-action-icon:hover::after {
            opacity: 1 !important;
            visibility: visible !important;
        }
        
        /* 面包屑样式 - 作为页面标题 */
        .breadcrumb { margin: 0; font-size: 18px; font-weight: 600; color: #333; }
        .breadcrumb-item { cursor: pointer; color: #1976d2; text-decoration: none; margin-right: 8px; }
        .breadcrumb-item:hover { text-decoration: underline; }
        .breadcrumb-item.active { color: #333; cursor: default; }
        .breadcrumb-item.active:hover { text-decoration: none; }
        .breadcrumb-separator { margin: 0 8px; color: #999; }
        
        .empty-state { text-align: center; padding: 60px 20px; color: #666; }
        .empty-icon { font-size: 48px; margin-bottom: 16px; opacity: 0.5; }
        .loading { text-align: center; padding: 40px; color: #666; }

        .page-header { display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; background: white; border-bottom: 1px solid #e9ecef; }
        .page-title { margin: 0; font-size: 18px; font-weight: 600; color: #333; }
        .batch-actions { display: flex; align-items: center; gap: 12px; }
        .batch-info { color: #666; font-size: 14px; font-weight: 500; }
        .action-buttons { display: flex; gap: 8px; }
        .action-item { position: relative; cursor: pointer; transition: all 0.2s; padding: 4px; border-radius: 6px; }
        .action-item:hover { background: #f8f9fa; }
        .action-icon { width: 22px; height: 22px; border: none; border-radius: 50%; background: #f8f9fa; font-size: 12px; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; justify-content: center; }
        .action-icon:hover { transform: scale(1.1); }
        .action-icon.copy { background: #e3f2fd; color: #1976d2; }
        .action-icon.revoke { background: #ffebee; color: #d32f2f; }
        .action-icon.cancel { background: #f5f5f5; color: #757575; }
        
        /* 悬浮提示样式 */
        .action-item::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: -30px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s, visibility 0.3s;
            z-index: 1000;
            pointer-events: none;
        }
        .action-item.show-tooltip::after {
            opacity: 1;
            visibility: visible;
        }

        .pagination { display: flex; justify-content: center; align-items: center; gap: 10px; margin-top: 20px; padding: 20px; flex-shrink: 0; }
        .page-btn { padding: 8px 12px; border: 1px solid #ddd; background: white; border-radius: 4px; cursor: pointer; transition: all 0.2s; user-select: none; }
        .page-btn:hover:not(:disabled) { background: #f8f9fa; border-color: #007bff; }
        .page-btn:disabled { opacity: 0.5; cursor: not-allowed; background: #f5f5f5; }
        .page-info { color: #666; font-size: 14px; }

        @media (max-width: 768px) {
            .file-container { padding: 10px; }
            .file-table th, .file-table td { padding: 8px 12px; font-size: 13px; }
            .file-actions { flex-direction: column; gap: 4px; }
            .action-btn { padding: 3px 6px; font-size: 11px; min-width: 35px; }
        }

        /* 高亮关键词样式：黄色背景、加粗文字（与home.html统一） */
        .highlight-keyword {
            background-color: #fff143;
            font-weight: bold;
            padding: 0 2px; /* 可选：增加内边距让高亮更明显 */
        }
    </style>
</head>
<body>
    <div class="file-container">
        <div class="file-list">
            <!-- 页面标题和批量操作按钮 -->
            <div class="page-header">
                <div class="breadcrumb" id="breadcrumb" style="display: block;">
                    <span class="breadcrumb-item active">我的分享</span>
                </div>
                <div class="batch-actions">
                    <div class="batch-info">
                        <span id="selectedCount">已选择 0 项</span>
                        <span id="pageSizeInfo" style="margin-left: 10px; color: #999; font-size: 12px;">每页显示: <span id="currentPageSize">10</span> 条</span>
                    </div>
                    <div class="action-buttons">
                        <div class="action-item" onclick="batchCopyLink()" data-tooltip="复制链接">
                            <button class="action-icon copy">📋</button>
                        </div>
                        <div class="action-item" onclick="batchRevoke()" data-tooltip="撤销分享">
                            <button class="action-icon revoke">🚫</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="file-list-wrapper">
                <table class="file-table">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAll"></th>
                            <th>文件名</th>
                            <th>分享链接</th>
                            <th>密码</th>
                            <th>有效期</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="shareTableBody">
                        <tr>
                            <td colspan="6" class="loading"><div>正在加载分享列表...</div></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="pagination" id="pagination" style="display: none;">
            <button class="page-btn" id="prevBtn">上一页</button>
            <span class="page-info" id="pageInfo">第 1 页，共 1 页</span>
            <button class="page-btn" id="nextBtn">下一页</button>
        </div>
    </div>

    <!-- 重命名模态框 -->
    <div id="renameModal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>重命名</h3>
                <span class="close" onclick="closeRenameModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="renameFileName">新名称：</label>
                    <input type="text" id="renameFileName" placeholder="请输入新名称" maxlength="100">
                    <input type="hidden" id="renameFileId">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeRenameModal()">取消</button>
                <button class="btn btn-primary" onclick="executeRename()">确定</button>
            </div>
        </div>
    </div>

    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 1;
        let currentUserId = null; // 用户ID（从session获取）
        let currentParentId = 0;
        let breadcrumbPath = []; // 面包屑路径

        // 新增：点击回收站页面空白区域时，通知父窗口隐藏搜索提示面板
        document.addEventListener('click', (e) => {
            // 判断点击是否在页面主体区域（非搜索相关元素）
            const isInMainArea = !e.target.closest('.search-box') &&
                !e.target.closest('.search-suggest') &&
                !e.target.closest('#searchInput');
            if (isInMainArea && parent && parent.hideSuggestPanel) {
                parent.hideSuggestPanel();
            }
        });

        // 根据窗口大小计算每页显示数量
        function calculatePageSize() {
            const windowHeight = window.innerHeight;
            const windowWidth = window.innerWidth;
            
            // 计算可用高度（减去头部、分页等固定元素的高度）
            const headerHeight = 60; // 页面头部高度
            const paginationHeight = 80; // 分页区域高度
            const availableHeight = windowHeight - headerHeight - paginationHeight;
            
            // 计算每行高度（包括边框、内边距）
            const rowHeight = 50; // 每行大约50px高度
            
            // 计算可显示的行数
            const maxRows = Math.floor(availableHeight / rowHeight);
            
            // 根据窗口宽度调整
            let calculatedPageSize = maxRows;
            
            // 小屏幕设备优化
            if (windowWidth < 768) {
                calculatedPageSize = Math.min(maxRows, 3);
        } else if (windowWidth < 1200) {
            calculatedPageSize = Math.min(maxRows, 5);
        } else {
            calculatedPageSize = Math.min(maxRows, 8);
        }
            
            // 确保最小和最大值
            return Math.max(3, Math.min(calculatedPageSize, 20));
        }

        // 更新页面大小
        function updatePageSize() {
            const newPageSize = calculatePageSize();
            if (newPageSize !== pageSize) {
                pageSize = newPageSize;
                currentPage = 1; // 重置到第一页
                updatePageSizeDisplay(); // 更新显示
                loadShareList(); // 重新加载数据
            }
        }

        // 更新页面大小显示
        function updatePageSizeDisplay() {
            const currentPageSizeElement = document.getElementById('currentPageSize');
            if (currentPageSizeElement) {
                currentPageSizeElement.textContent = pageSize;
            }
        }

        // 检查登录状态并初始化
        async function initSharesPage() {
            try {
                // 先检查登录状态
                const response = await fetch('/api/user/check-login');
                const result = await response.json();
                
                if (result.loggedIn && result.user) {
                    // 已登录：设置用户ID
                    currentUserId = result.user.id;
                    
                    // 如果父窗口存在，也更新父窗口的全局变量
                    if (window.parent && window.parent.CURRENT_USER_ID !== currentUserId) {
                        window.parent.CURRENT_USER_ID = currentUserId;
                    }
                    
                    // 初始化页面
                    pageSize = calculatePageSize();
                    updatePageSizeDisplay();
                    updateBreadcrumb();
                    loadShareList();
                    setupEventListeners();
                    initTooltips();
                } else {
                    // 未登录：如果是iframe，通知父窗口跳转；否则直接跳转
                    if (window.parent && window.parent !== window) {
                        window.parent.location.href = '/login';
                    } else {
                        window.location.href = '/login';
                    }
                }
            } catch (error) {
                console.error('检查登录状态失败:', error);
                // 检查失败时也跳转到登录页
                if (window.parent && window.parent !== window) {
                    window.parent.location.href = '/login';
                } else {
                    window.location.href = '/login';
                }
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 延迟一点，确保父窗口的登录检查完成
            setTimeout(() => {
                initSharesPage();
            }, 100);
        });

        // 监听窗口大小变化
        let resizeTimeout;
        window.addEventListener('resize', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(updatePageSize, 300); // 防抖，300ms后执行
        });

        function setupEventListeners() {
            const selectAllCheckbox = document.getElementById('selectAll');
            if (selectAllCheckbox) {
                selectAllCheckbox.addEventListener('change', function() {
                    const checkboxes = document.querySelectorAll('.file-checkbox');
                    checkboxes.forEach(checkbox => { checkbox.checked = this.checked; });
                    updateBatchToolbar();
                });
            }

            // 监听单个复选框变化
            document.addEventListener('change', function(e) {
                if (e.target.classList.contains('file-checkbox')) {
                    updateBatchToolbar();
                }
            });

            const prevBtn = document.getElementById('prevBtn');
            const nextBtn = document.getElementById('nextBtn');
            if (prevBtn) {
                prevBtn.addEventListener('click', function(e) {
                    e.preventDefault(); e.stopPropagation();
                    if (currentPage > 1) { currentPage--; loadShareList(); }
                });
            }
            if (nextBtn) {
                nextBtn.addEventListener('click', function(e) {
                    e.preventDefault(); e.stopPropagation();
                    if (currentPage < totalPages) { currentPage++; loadShareList(); }
                });
            }
        }

        async function loadShareList() {
            try {
                const tbody = document.getElementById('shareTableBody');
                tbody.innerHTML = '<tr><td colspan="5" class="loading"><div>正在加载分享列表...</div></td></tr>';

                // 预期后端分享接口
                const response = await fetch(`/api/share/list?pageSize=${pageSize}&pageNo=${currentPage}&userId=${currentUserId}`);
                const result = await response.json();

                if (result.success) {
                    renderShareList(result.data);
                } else {
                    showError('加载分享列表失败: ' + (result.message || ''));
                }
            } catch (error) {
                console.error('加载分享列表失败:', error);
                showError('网络错误，请稍后重试');
            }
        }

        function renderShareList(data) {
            const tbody = document.getElementById('shareTableBody');
            const pagination = document.getElementById('pagination');

            if (!data || !data.list || data.list.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" class="empty-state">
                            <div class="empty-icon">🔗</div>
                            <div>暂无分享</div>
                        </td>
                    </tr>
                `;
                pagination.style.display = 'none';
                return;
            }

            currentPage = data.pageNum || 1;
            totalPages = data.pages || 1;
            updatePagination();

            window.shareList = data.list;

            tbody.innerHTML = '';
            data.list.forEach(item => {
                const row = document.createElement('tr');
                const isDirectory = item.isDirectory === 1 || item.isDirectory === true;
                // 1. 优先取高亮文件名，无则取原始文件名（核心高亮逻辑）
                const displayFileName = item.highlightFileName || item.fileName || '未知文件';
                const clickHandler = isDirectory ? `onclick="enterFolder(${item.id}, '${item.fileName}')"` : '';
                const cursorStyle = isDirectory ? 'style="cursor: pointer;"' : '';
                const link = item.shareUrl || (location.origin + '/share/' + (item.shareCode || item.code || item.id));
                const password = item.password || '';
                const passwordDisplay = password ?
                    `<span class="password-display" title="点击复制密码" onclick="copyPassword('${password}')">${password}</span>` :
                    `<span class="password-display">未设置</span>`;

                // 2. 渲染行结构：给文件名div加 data-file-name 标识，暂不填充内容
                row.innerHTML = `
            <td><input type="checkbox" class="file-checkbox" data-id="${item.id}"></td>
            <td ${clickHandler} ${cursorStyle}>
                <div class="file-item">
                    <div class="file-icon">${getFileIcon(item.fileName, item.isDirectory)}</div>
                    <!-- 关键：加标识用于后续填充高亮内容 -->
                    <div class="file-name" data-file-name="true"></div>
                </div>
            </td>
            <td>
                <div class="file-name" title="${link}">${link}</div>
            </td>
            <td>
                ${passwordDisplay}
            </td>
            <td>
                <div>${formatExpire(item.expireTime)}</div>
            </td>
            <td>
                <div class="file-actions">
                    <div class="action-item" onclick="copyLink('${link}')" data-tooltip="复制链接"><button class="action-icon copy">📋</button></div>
                    <div class="action-item" onclick="revokeShare(${item.id})" data-tooltip="取消分享"><button class="action-icon delete">🗑️</button></div>
                </div>
            </td>
        `;
                tbody.appendChild(row);

                // 3. 用原生JS找到文件名div，通过 innerHTML 解析高亮标签（核心步骤）
                const fileNameDiv = row.querySelector('[data-file-name="true"]');
                if (fileNameDiv) {
                    fileNameDiv.innerHTML = displayFileName; // 解析 <span class="highlight-keyword"> 标签
                }
            });

            pagination.style.display = 'flex';
            initTooltips();
        }

        function updatePagination() {
            const prevBtn = document.getElementById('prevBtn');
            const nextBtn = document.getElementById('nextBtn');
            const pageInfo = document.getElementById('pageInfo');
            if (prevBtn && nextBtn && pageInfo) {
                prevBtn.disabled = currentPage <= 1;
                nextBtn.disabled = currentPage >= totalPages;
                pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
            }
        }

        function getFileIcon(fileName, isDirectory) {
            if (!fileName) return '📄';
            
            // 如果是目录，返回目录图标
            if (isDirectory === 1 || isDirectory === true) {
                return '📁';
            }
            
            const ext = fileName.split('.').pop().toLowerCase();
            const iconMap = { 'pdf':'📄','doc':'📝','docx':'📝','xls':'📊','xlsx':'📊','ppt':'📋','pptx':'📋','txt':'📄','jpg':'🖼️','jpeg':'🖼️','png':'🖼️','gif':'🖼️','mp4':'🎥','avi':'🎥','mov':'🎥','mp3':'🎵','wav':'🎵','zip':'📦','rar':'📦','7z':'📦','folder':'📁' };
            return iconMap[ext] || '📄';
        }

        // 进入目录
        function enterFolder(folderId, folderName) {
            currentParentId = folderId;
            currentPage = 1;
            breadcrumbPath.push({id: folderId, name: folderName});
            updateBreadcrumb();
            loadShareList();
        }
        
        // 返回根目录
        function goToRoot() {
            currentParentId = 0;
            currentPage = 1;
            breadcrumbPath = [];
            updateBreadcrumb();
            loadShareList();
        }
        
        // 更新面包屑显示
        function updateBreadcrumb() {
            const breadcrumb = document.getElementById('breadcrumb');
            if (breadcrumbPath.length === 0) {
                // 在根目录时显示"我的分享"
                breadcrumb.style.display = 'block';
                breadcrumb.innerHTML = '<span class="breadcrumb-item active">我的分享</span>';
            } else {
                // 在子目录时显示完整路径
                breadcrumb.style.display = 'block';
                let html = '<span class="breadcrumb-item" onclick="goToRoot()">我的分享</span>';
                
                breadcrumbPath.forEach((item, index) => {
                    html += '<span class="breadcrumb-separator">/</span>';
                    html += `<span class="breadcrumb-item" onclick="goToBreadcrumb(${index})">${item.name}</span>`;
                });
                
                breadcrumb.innerHTML = html;
            }
        }
        
        // 点击面包屑导航
        function goToBreadcrumb(index) {
            breadcrumbPath = breadcrumbPath.slice(0, index + 1);
            if (breadcrumbPath.length === 0) {
                goToRoot();
            } else {
                const target = breadcrumbPath[breadcrumbPath.length - 1];
                currentParentId = target.id;
                currentPage = 1;
                updateBreadcrumb();
                loadShareList();
            }
        }

        function formatExpire(expireTime) {
            if (!expireTime) return '永久有效';
            try {
                const date = new Date(expireTime);
                return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
            } catch (e) {
                return expireTime;
            }
        }

        function showError(message) {
            const tbody = document.getElementById('shareTableBody');
            tbody.innerHTML = `
                <tr>
                    <td colspan="6" class="empty-state">
                        <div class="empty-icon">❌</div>
                        <div>${message}</div>
                    </td>
                </tr>
            `;
        }

        // 更新批量操作工具栏
        function updateBatchToolbar() {
            const selectedCheckboxes = document.querySelectorAll('.file-checkbox:checked');
            const selectedCount = document.getElementById('selectedCount');
            selectedCount.textContent = `已选择 ${selectedCheckboxes.length} 项`;
        }

        // 初始化悬浮提示功能
        function initTooltips() {
            const actionItems = document.querySelectorAll('.action-item');
            actionItems.forEach(item => {
                // 检查是否已经绑定了事件监听器
                if (item.hasAttribute('data-tooltip-initialized')) {
                    return; // 跳过已经初始化的元素
                }
                
                let hoverTimer;
                
                item.addEventListener('mouseenter', function() {
                    hoverTimer = setTimeout(() => {
                        this.classList.add('show-tooltip');
                    }, 500); // 0.5秒延迟
                });
                
                item.addEventListener('mouseleave', function() {
                    clearTimeout(hoverTimer);
                    this.classList.remove('show-tooltip');
                });
                
                // 标记为已初始化
                item.setAttribute('data-tooltip-initialized', 'true');
            });
        }

        // 获取选中的文件ID列表
        function getSelectedFileIds() {
            const selectedCheckboxes = document.querySelectorAll('.file-checkbox:checked');
            return Array.from(selectedCheckboxes).map(checkbox => checkbox.dataset.id);
        }


        // 批量复制链接
        async function batchCopyLink() {
            const selectedIds = getSelectedFileIds();
            if (selectedIds.length === 0) {
                alert('请先选择要复制链接的分享');
                return;
            }

            try {
                // 获取所有分享信息，构建链接列表
                const checkboxes = document.querySelectorAll('.file-checkbox:checked');
                const links = [];
                
                checkboxes.forEach(checkbox => {
                    const row = checkbox.closest('tr');
                    if (row) {
                        // 从第三列获取分享链接
                        const linkCell = row.cells[2];
                        if (linkCell) {
                            const linkDiv = linkCell.querySelector('.file-name');
                            if (linkDiv) {
                                const link = linkDiv.textContent.trim();
                                if (link) {
                                    links.push(link);
                                }
                            }
                        }
                    }
                });

                if (links.length === 0) {
                    alert('未找到分享链接');
                    return;
                }

                // 复制所有链接到剪贴板（换行分隔）
                const linkText = links.join('\n');
                await navigator.clipboard.writeText(linkText);
                alert(`已复制 ${links.length} 个分享链接到剪贴板`);
            } catch (error) {
                console.error('批量复制链接失败:', error);
                alert('批量复制链接失败，请稍后重试');
            }
        }

        // 批量撤销分享
        async function batchRevoke() {
            const selectedIds = getSelectedFileIds();
            if (selectedIds.length === 0) {
                alert('请先选择要撤销的分享');
                return;
            }

            if (!confirm(`确定要撤销选中的 ${selectedIds.length} 个分享吗？`)) return;

            try {
                const promises = selectedIds.map(id => 
                    fetch(`/api/share/${id}`, { method: 'DELETE' })
                        .then(resp => resp.json())
                );
                
                const results = await Promise.all(promises);
                const successCount = results.filter(r => r.success).length;
                
                if (successCount === selectedIds.length) {
                    alert(`成功撤销 ${successCount} 个分享`);
                } else {
                    alert(`撤销完成，成功 ${successCount} 个，失败 ${selectedIds.length - successCount} 个`);
                }
                
                await loadShareList();
            } catch (error) {
                alert('批量撤销失败：' + error.message);
            }
        }

        async function revokeShare(shareId) {
            if (!confirm('确定要取消分享吗？')) return;
            try {
                const resp = await fetch(`/api/share/${shareId}`, { method: 'DELETE' });
                if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
                const json = await resp.json();
                if (!json.success) throw new Error(json.message || '取消失败');
                await loadShareList();
                alert('已取消分享');
            } catch (e) {
                alert('取消分享失败：' + e.message);
            }
        }

        function copyLink(link) {
            try {
                navigator.clipboard.writeText(link).then(() => alert('已复制链接')).catch(() => fallbackCopy(link));
            } catch (e) { fallbackCopy(link); }
        }

        function copyPassword(password) {
            try {
                navigator.clipboard.writeText(password).then(() => alert('已复制密码')).catch(() => {
                    // 降级方案
                    const textarea = document.createElement('textarea');
                    textarea.value = password;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textarea);
                    alert('已复制密码');
                });
            } catch (e) {
                alert('复制密码失败，请手动复制');
            }
        }

        function fallbackCopy(text) {
            const input = document.createElement('input');
            input.value = text; document.body.appendChild(input); input.select();
            document.execCommand('copy'); document.body.removeChild(input);
            alert('已复制链接');
        }

        // 更新面包屑导航（供父窗口调用）
        function updateBreadcrumbNav(currentPath) {
            const breadcrumb = document.getElementById('breadcrumb');
            if (breadcrumb) {
                breadcrumb.style.display = 'block';
                console.log('iframe收到面包屑更新:', currentPath); // 调试日志
                
                // 如果传入了currentPath参数，直接使用该参数
                if (currentPath) {
                    breadcrumb.innerHTML = `<span class="breadcrumb-item active">${currentPath}</span>`;
                } else {
                    // 如果没有传入参数，使用原有的逻辑
                    if (breadcrumbPath.length === 0) {
                        breadcrumb.innerHTML = '<span class="breadcrumb-item active">我的分享</span>';
                    } else {
                        // 如果当前在子目录，显示完整路径
                        let html = '<span class="breadcrumb-item" onclick="goToRoot()">我的分享</span>';
                        breadcrumbPath.forEach((item, index) => {
                            html += '<span class="breadcrumb-separator">/</span>';
                            html += `<span class="breadcrumb-item" onclick="goToBreadcrumb(${index})">${item.name}</span>`;
                        });
                        breadcrumb.innerHTML = html;
                    }
                }
            }
        }
        
        // 将函数暴露给父窗口
        window.updateBreadcrumbNav = updateBreadcrumbNav;
        window.performSearch = performSearch;
        window.applyAdvancedSearch = applyAdvancedSearch;
        window.openRenameModal = openRenameModal;
        window.closeRenameModal = closeRenameModal;
        window.executeRename = executeRename;

        // --- 搜索功能 ---
        // 执行搜索
        function performSearch(keyword) {
            console.log('执行分享搜索:', keyword);
            
            // 这里可以调用后端搜索API
            // 暂时使用模拟数据
            const searchResults = mockShareFiles.filter(file => 
                file.name.toLowerCase().includes(keyword.toLowerCase()) ||
                file.type.toLowerCase().includes(keyword.toLowerCase())
            );
            
            // 更新文件列表
            renderShareList(searchResults);
            
            // 更新面包屑显示搜索状态
            updateBreadcrumbNav(`搜索结果: "${keyword}"`);
        }

        // 应用高级搜索
        function applyAdvancedSearch(params) {
            console.log('应用分享高级搜索:', params);
            
            let results = [...mockShareFiles];
            
            // 关键词搜索
            if (params.keyword) {
                results = results.filter(file => 
                    file.name.toLowerCase().includes(params.keyword.toLowerCase()) ||
                    file.type.toLowerCase().includes(params.keyword.toLowerCase())
                );
            }
            
            // 文件类型过滤
            if (params.fileType) {
                results = results.filter(file => file.type === params.fileType);
            }
            
            // 时间范围过滤
            if (params.timeRange) {
                const now = new Date();
                let startDate;
                
                switch (params.timeRange) {
                    case 'today':
                        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
                        break;
                    case 'week':
                        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                        break;
                    case 'month':
                        startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
                        break;
                    case 'year':
                        startDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
                        break;
                    case 'custom':
                        if (params.startDate && params.endDate) {
                            startDate = new Date(params.startDate);
                            const endDate = new Date(params.endDate);
                            results = results.filter(file => {
                                const fileDate = new Date(file.date);
                                return fileDate >= startDate && fileDate <= endDate;
                            });
                        }
                        break;
                }
                
                if (params.timeRange !== 'custom' && startDate) {
                    results = results.filter(file => {
                        const fileDate = new Date(file.date);
                        return fileDate >= startDate;
                    });
                }
            }
            
            // 文件大小过滤
            if (params.fileSizeRange) {
                results = results.filter(file => {
                    if (file.type === 'folder') return true;
                    
                    const sizeStr = file.size;
                    if (!sizeStr || sizeStr === '-') return true;
                    
                    let sizeInMB = 0;
                    if (sizeStr.includes('KB')) {
                        sizeInMB = parseFloat(sizeStr) / 1024;
                    } else if (sizeStr.includes('MB')) {
                        sizeInMB = parseFloat(sizeStr);
                    } else if (sizeStr.includes('GB')) {
                        sizeInMB = parseFloat(sizeStr) * 1024;
                    }
                    
                    switch (params.fileSizeRange) {
                        case '0-1MB':
                            return sizeInMB < 1;
                        case '1-10MB':
                            return sizeInMB >= 1 && sizeInMB < 10;
                        case '10-100MB':
                            return sizeInMB >= 10 && sizeInMB < 100;
                        case '100MB+':
                            return sizeInMB >= 100;
                        case 'custom':
                            if (params.minSize && params.maxSize) {
                                return sizeInMB >= parseFloat(params.minSize) && sizeInMB <= parseFloat(params.maxSize);
                            }
                            break;
                    }
                    return true;
                });
            }
            
            // 排序
            if (params.sortBy) {
                results.sort((a, b) => {
                    let aVal, bVal;
                    
                    switch (params.sortBy) {
                        case 'name':
                            aVal = a.name.toLowerCase();
                            bVal = b.name.toLowerCase();
                            break;
                        case 'size':
                            aVal = getSizeInBytes(a.size);
                            bVal = getSizeInBytes(b.size);
                            break;
                        case 'time':
                            aVal = new Date(a.date);
                            bVal = new Date(b.date);
                            break;
                        case 'type':
                            aVal = a.type;
                            bVal = b.type;
                            break;
                        default:
                            return 0;
                    }
                    
                    if (aVal < bVal) return params.sortOrder === 'asc' ? -1 : 1;
                    if (aVal > bVal) return params.sortOrder === 'asc' ? 1 : -1;
                    return 0;
                });
            }
            
            // 更新文件列表
            renderShareList(results);
            
            // 更新面包屑显示搜索状态
            let searchDesc = '搜索结果';
            if (params.keyword) {
                searchDesc += `: "${params.keyword}"`;
            }
            updateBreadcrumbNav(searchDesc);
        }

        // 辅助函数：将文件大小字符串转换为字节数
        function getSizeInBytes(sizeStr) {
            if (!sizeStr || sizeStr === '-') return 0;
            
            const num = parseFloat(sizeStr);
            if (sizeStr.includes('KB')) return num * 1024;
            if (sizeStr.includes('MB')) return num * 1024 * 1024;
            if (sizeStr.includes('GB')) return num * 1024 * 1024 * 1024;
            return num;
        }

        // --- 重命名功能 ---
        // 打开重命名模态框
        function openRenameModal(fileId, currentName) {
            document.getElementById('renameFileId').value = fileId;
            document.getElementById('renameFileName').value = currentName;
            document.getElementById('renameModal').style.display = 'flex';
            
            // 选中输入框中的文本（去掉扩展名）
            const input = document.getElementById('renameFileName');
            setTimeout(() => {
                input.focus();
                const lastDotIndex = currentName.lastIndexOf('.');
                if (lastDotIndex > 0) {
                    input.setSelectionRange(0, lastDotIndex);
                } else {
                    input.select();
                }
            }, 100);
        }

        // 关闭重命名模态框
        function closeRenameModal() {
            document.getElementById('renameModal').style.display = 'none';
            document.getElementById('renameFileName').value = '';
            document.getElementById('renameFileId').value = '';
        }

        // 执行重命名
        async function executeRename() {
            const fileId = document.getElementById('renameFileId').value;
            const newName = document.getElementById('renameFileName').value.trim();
            
            if (!newName) {
                alert('请输入新名称');
                return;
            }
            
            // 验证名称格式
            if (newName.includes('/') || newName.includes('\\') || newName.includes(':') || 
                newName.includes('*') || newName.includes('?') || newName.includes('"') || 
                newName.includes('<') || newName.includes('>') || newName.includes('|')) {
                alert('名称包含非法字符');
                return;
            }
            
            try {
                const response = await fetch('/api/userfile/rename', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `fileId=${fileId}&newName=${encodeURIComponent(newName)}&userId=${currentUserId}`
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('重命名成功');
                    closeRenameModal();
                    // 重新加载文件列表
                    await loadShareList();
                } else {
                    alert('重命名失败：' + result.message);
                }
            } catch (error) {
                console.error('重命名失败:', error);
                alert('重命名失败：' + error.message);
            }
        }
    </script>
</body>
</html>


